//
//  ChapterListViewController.m
//  shuyou
//
//  Created by 吴超飞 on 2018/12/13.
//  Copyright © 2018 Moton. All rights reserved.
//

#import "ChapterListViewController.h"
#import "ReaderBookModel.h"
#import "MBProgressHUD.h"
#import "ReaderViewController.h"

@interface ChapterListViewController ()<UITableViewDataSource,UITableViewDelegate>{
    BOOL isDesc;//是否倒序排列
    BOOL isExcuting;
}

@property (nonatomic,retain) Book *book;
@property (nonatomic,retain) NSArray *datas;
@property (nonatomic,retain) UITableView *tableview;
@property (nonatomic,retain) UISlider *slider;
@property (nonatomic,retain) MBProgressHUD *HUD;

@end

@implementation ChapterListViewController

-(instancetype)initWithBook:(Book *)book{
    
    self = [super init];
    
    if (self) {
        _book = book;
    }
    
    return self;
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.automaticallyAdjustsScrollViewInsets = NO;//继承于UIScrollView的控件不会向下滚动64的高度
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
    self.navigationController.navigationBar.tintColor = MTConfigColor(@"MTNavigationBar_leftItem_Color");
    
    [self createRightSortItem];
    [self addTableview];
    [self addSlider];
    [self loadData];
}

-(void)addTableview{
    
    UITableView *tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, MTScreenW, MTScreenH-SafeAreaTopHeight) style:UITableViewStylePlain];
    tableview.delegate = self;
    tableview.dataSource = self;
    tableview.separatorInset = UIEdgeInsetsMake(15,0,0,0);
    tableview.separatorColor = [ReaderGlobalModel shareModel].readerConfig.IsNight? MTConfigColor(@"MTBookMarkCatalog_tableviewSeparatorNight_Color"):MTConfigColor(@"MTBookMarkCatalog_tableviewSeparatorDay_Color");
    tableview.showsVerticalScrollIndicator = NO;
    [self.view insertSubview:tableview atIndex:1];
    _tableview = tableview;
    _tableview.layer.borderColor = _tableview.separatorColor.CGColor;
}

-(void)addSlider{
    
    UIImage *img = [self imageByApplyingAlpha:0 image:[UIImage imageNamed:@"mulu_huadong_sl"]];
    
    UISlider *slider = [[UISlider alloc] initWithFrame:CGRectMake(0,0,self.tableview.height,img.size.width/2)];
    
    //设置未滑动位置背景图片
    [slider setMinimumTrackImage:img forState:UIControlStateNormal];
    //设置已滑动位置背景图
    [slider setMaximumTrackImage:img forState:UIControlStateNormal];
    //设置滑块图标图片
    UIImage *slImg = [self imageByApplyingAlpha:0.7 image:[UIImage imageNamed:@"mulu_huadong_sl"]];
    UIImage *thumbImg = [ReaderGlobalModel shareModel].readerConfig.IsNight?[UIImage imageNamed:@"mulu_huadong_nl"]:slImg;
    [slider setThumbImage:thumbImg forState:UIControlStateNormal];
    //设置点击滑块状态图标  滑动不显示，否则图标会跳动
    [slider setThumbImage:thumbImg forState:UIControlStateHighlighted];
    
    //设置旋转90度
    slider.transform = CGAffineTransformMakeRotation(M_PI_2);
    CGPoint cp = CGPointMake(MTScreenW-slider.width/2-10, self.tableview.centerY);
    slider.center = cp;
    //设置起始位置
    //slider.value=0.5;
    //设置背景颜色
    slider.backgroundColor = [UIColor clearColor];
    [slider addTarget:self action:@selector(sliderChange) forControlEvents:UIControlEventValueChanged];
    [self.view insertSubview:slider atIndex:2];
    _slider = slider;
}

-(void)sliderChange {
    
    if (!_datas || _datas.count == 0) return;
    [self.tableview scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:(_datas.count-1)*_slider.value inSection:0] atScrollPosition:UITableViewScrollPositionMiddle animated:NO];
}

- (void)createRightSortItem
{
    UIBarButtonItem *sortItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"sort_zhengxu"] style:UIBarButtonItemStylePlain target:self action:@selector(sort)];
    sortItem.tintColor = MTConfigColor(@"MTNavigationBar_leftItem_Color");
    self.navigationItem.rightBarButtonItem = sortItem;
}

-(void)sort{
    
    isDesc = !isDesc;
    if (isDesc) {
        self.navigationItem.rightBarButtonItem.image=[UIImage imageNamed:@"sort_daoxu"];
    }else{
        self.navigationItem.rightBarButtonItem.image=[UIImage imageNamed:@"sort_zhengxu"];
    }
    
    _datas = [self sortAndMarkdownArray:_datas];
    [self.tableview reloadData];
}

-(void)loadData{
    
    ReaderBookModel *readerbookModel = [[ReaderBookModel alloc] initWithBook:_book isMiddleIn:NO];
    [self showHUD];
    [readerbookModel getChapterList:^(NSMutableArray *list) {
        dispatch_async(dispatch_get_main_queue(), ^{
            _datas = [NSArray arrayWithArray:list];
            [self.tableview reloadData];
            [self hideHUD];
        });
    }];
}

-(MBProgressHUD *)HUD{
   
    if (!_HUD) {
        _HUD = [[MBProgressHUD alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
        _HUD.center = self.view.center;
    }
    return _HUD;
}

- (void)showHUD{
    
    [self.view addSubview:self.HUD];
    [self.view bringSubviewToFront:self.HUD];
    [self.HUD show:YES];
}

-(void)hideHUD{
    
    [self.HUD removeFromSuperview];
}

- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        cell.backgroundColor = [UIColor clearColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    if(_datas.count == 0 )return cell;
    
    Chapter *chapter;
    id obj = _datas[indexPath.row];
    if([obj isKindOfClass:[Chapter class]]){
        chapter=(Chapter *)obj;
    }else{
        return cell;
    }
    
    cell.textLabel.text = chapter.chaptername;
    
    return cell;
}

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
     return  _datas.count;
}

-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    Chapter *chapter;
    id obj = _datas[indexPath.row];
    
    if([obj isKindOfClass:[Chapter class]]){
        chapter=(Chapter *)obj;
        Book *rbook = [[Book alloc]init];
        rbook.bookid = _book.bookid;
        rbook.siteid = _book.siteid;
        rbook.bookname = _book.bookname;
        rbook.firstchapterid = chapter.chapterid;
        rbook.firstchaptername = chapter.chaptername;
        rbook.updatetime = chapter.updatetime;
        [self pushToReader:rbook isMiddleIn:YES];
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    CGFloat y = scrollView.contentOffset.y/(scrollView.contentSize.height-_tableview.height);
    _slider.value = y;
    
    _tableview.layer.borderWidth = scrollView.contentOffset.y == 0?0:0.5;
}

//正序逆序排列数据
- (NSArray *)sortAndMarkdownArray:(NSArray *)array {
    
    if([self isNeedResort:array]){
        array = [array sortedArrayUsingComparator:^NSComparisonResult(Chapter *obj1, Chapter *obj2) {
            //根据chapterorder字段排序，老版中已缓存列表中没有这个字段的直接根据chapterid排
            NSComparisonResult result = isDesc?[obj1.chapterorder integerValue]<[obj2.chapterorder integerValue]:[obj1.chapterorder integerValue]>[obj2.chapterorder integerValue];
            if(result==NSOrderedSame)
                result = isDesc?[obj1.chapterid integerValue]<[obj2.chapterid integerValue]:[obj1.chapterid integerValue]>[obj2.chapterid integerValue];
            return result;
        }];
    }
    
    return array;
}

-(BOOL)isNeedResort:(NSArray *)array{
    
    BOOL ret = NO;
    Chapter *firtst = [array firstObject];
    Chapter *last = [array lastObject];
    if(isDesc&&([firtst.chapterorder intValue]<[last.chapterorder intValue]||([firtst.chapterorder intValue]==[last.chapterorder intValue]&&[firtst.chapterid intValue]<[last.chapterid intValue]))){//逆序时，当前数据是正序的
        ret = YES;
    }
    if (!isDesc&&([firtst.chapterorder intValue]>[last.chapterorder intValue]||([firtst.chapterorder intValue]==[last.chapterorder intValue]&&[firtst.chapterid intValue]>[last.chapterid intValue]))) {//正序时，当前数据是逆序的
        ret = YES;
    }
    
    return ret;
}

- (void)pushToReader:(Book *)book isMiddleIn:(BOOL)ismid{
    
    if(!book)return;
    if(isExcuting)return;
    isExcuting = YES;
    
    ReaderBookModel *readerbookModel = [[ReaderBookModel alloc] initWithBook:book isMiddleIn:ismid];
    [self.view addSubview:self.HUD];
    [self.view bringSubviewToFront:self.HUD];
    [self.HUD show:YES];
    double time = 0;
    if(![readerbookModel isExistCurrentChapter]){
        self.HUD.labelText = kInfoNetLoad;
        time = [[NSDate date] timeIntervalSince1970];
    }else{
        self.HUD.labelText = kInfoLocalLoad;
    }
    
    [readerbookModel getInitPageDataComplete:^(NSDictionary *dict,TurnResult result) {
        
        NSArray *array = [dict objectForKey:@"data"];
        if(!dict||!array||[array count]==0||result==TurnNoNet){//未获取到内容
            [ToastView showMsg:kContentErrorNoNetInfo inView:self.view isCenter:YES];
            [self.HUD removeFromSuperview];
            return ;
        }
        
        double inteval = 0.0f;
        if(time>0)inteval = 2.0 - ([[NSDate date] timeIntervalSince1970]-time);
        inteval = inteval<0?0:inteval;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, inteval * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
            [self.HUD removeFromSuperview];
            ReaderViewController *reader = [[ReaderViewController alloc] init];
            reader.readerBookModel = readerbookModel;
            [reader loadPageviewDatasource:dict];
            
            [self.navigationController pushViewController:reader animated:YES];
            isExcuting = NO;
        });
    }];
}

/**
 *  转换图片
 */
- (UIImage *)imageByApplyingAlpha:(CGFloat)alpha image:(UIImage*)image
{
    UIGraphicsBeginImageContextWithOptions(image.size, NO, 0.0f);
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGRect area = CGRectMake(0, 0, image.size.width, image.size.height);
    CGContextScaleCTM(ctx, 1, -1);
    CGContextTranslateCTM(ctx, 0, -area.size.height);
    CGContextSetBlendMode(ctx, kCGBlendModeMultiply);
    CGContextSetAlpha(ctx, alpha);
    CGContextDrawImage(ctx, area, image.CGImage);
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return newImage;
}

@end
